import { useState, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { 
  ArrowLeft, Moon, Sun, Globe, 
  Trash2, Download, Upload, RefreshCw,
  Palette, Smartphone,
  Shield, Database, HelpCircle, Bot, ChevronRight
} from 'lucide-react'
import { getVersionInfo } from '../utils/version'
import FloatingAISettings from '../components/FloatingAISettings'

interface AppSettings {
  theme: 'light' | 'dark' | 'system'
  language: 'zh' | 'en'
  autoBackup: boolean
  weekStart: 'monday' | 'sunday'
}

const defaultSettings: AppSettings = {
  theme: 'light',
  language: 'zh',
  autoBackup: true,
  weekStart: 'monday'
}

export default function SettingsPage() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const activeTab = searchParams.get('tab') || 'general'
  
  const [settings, setSettings] = useState<AppSettings>(defaultSettings)
  const [isLoading, setIsLoading] = useState(false)
  const [showAISettings, setShowAISettings] = useState(false)

  useEffect(() => {
    // 从localStorage加载设置
    const savedSettings = localStorage.getItem('aide_settings')
    if (savedSettings) {
      try {
        setSettings({ ...defaultSettings, ...JSON.parse(savedSettings) })
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    }
  }, [])

  const updateSetting = <K extends keyof AppSettings>(key: K, value: AppSettings[K]) => {
    const newSettings = { ...settings, [key]: value }
    setSettings(newSettings)
    localStorage.setItem('aide_settings', JSON.stringify(newSettings))
    
    // 应用主题设置
    if (key === 'theme') {
      applyTheme(value as string)
    }
  }

  const applyTheme = (theme: string) => {
    const root = document.documentElement
    if (theme === 'dark') {
      root.classList.add('dark')
    } else if (theme === 'light') {
      root.classList.remove('dark')
    } else {
      // system theme
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      if (prefersDark) {
        root.classList.add('dark')
      } else {
        root.classList.remove('dark')
      }
    }
  }

  const handleExportSettings = () => {
    const dataStr = JSON.stringify(settings, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `aide-settings-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  const handleImportSettings = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.json'
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0]
      if (file) {
        const reader = new FileReader()
        reader.onload = (e) => {
          try {
            const importedSettings = JSON.parse(e.target?.result as string)
            setSettings({ ...defaultSettings, ...importedSettings })
            localStorage.setItem('aide_settings', JSON.stringify(importedSettings))
            alert('设置导入成功！')
          } catch (error) {
            alert('设置文件格式错误！')
          }
        }
        reader.readAsText(file)
      }
    }
    input.click()
  }

  const handleResetSettings = () => {
    if (confirm('确定要重置所有设置吗？此操作不可撤销。')) {
      setSettings(defaultSettings)
      localStorage.removeItem('aide_settings')
      applyTheme('light')
      alert('设置已重置！')
    }
  }

  const handleClearCache = async () => {
    setIsLoading(true)
    try {
      // 清除各种缓存
      localStorage.removeItem('aide_dismissed_suggestions')
      localStorage.removeItem('aide_accepted_suggestions')
      localStorage.removeItem('aide_suggestions_cache')
      localStorage.removeItem('aide_suggestions_cache_time')
      
      // 清除Service Worker缓存
      if ('caches' in window) {
        const cacheNames = await caches.keys()
        await Promise.all(cacheNames.map(cacheName => caches.delete(cacheName)))
      }
      
      alert('缓存清理完成！')
    } catch (error) {
      alert('缓存清理失败！')
    } finally {
      setIsLoading(false)
    }
  }

  const tabs = [
    { id: 'general', name: '常规', icon: Palette },

    { id: 'data', name: '数据', icon: Database },
    { id: 'about', name: '关于', icon: HelpCircle }
  ]



  const renderGeneralSettings = () => (
    <div className="space-y-4">
      {/* 主题设置 */}
      <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
          <Palette size={18} />
          外观主题
        </h3>
        <div className="space-y-3">
          {[
            { value: 'light', label: '浅色模式', icon: Sun },
            { value: 'dark', label: '深色模式', icon: Moon },
            { value: 'system', label: '跟随系统', icon: Smartphone }
          ].map(option => (
            <button
              key={option.value}
              onClick={() => updateSetting('theme', option.value as any)}
              className={`w-full flex items-center gap-3 p-3 rounded-xl border transition-all ${
                settings.theme === option.value
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
              }`}
            >
              <option.icon size={18} />
              <span className="font-medium">{option.label}</span>
              {settings.theme === option.value && (
                <div className="ml-auto w-2 h-2 bg-blue-600 rounded-full"></div>
              )}
            </button>
          ))}
        </div>
      </div>

      {/* 语言设置 */}
      <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
          <Globe size={18} />
          语言设置
        </h3>
        <div className="space-y-3">
          {[
            { value: 'zh', label: '简体中文' },
            { value: 'en', label: 'English' }
          ].map(option => (
            <button
              key={option.value}
              onClick={() => updateSetting('language', option.value as any)}
              className={`w-full flex items-center justify-between p-3 rounded-xl border transition-all ${
                settings.language === option.value
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
              }`}
            >
              <span className="font-medium">{option.label}</span>
              {settings.language === option.value && (
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
              )}
            </button>
          ))}
        </div>
      </div>
    </div>
  )



  const renderDataSettings = () => (
    <div className="space-y-4">
      {/* 数据管理 */}
      <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
          <Database size={18} />
          数据管理
        </h3>
        <div className="space-y-3">
          <button
            onClick={handleExportSettings}
            className="w-full flex items-center gap-3 p-3 bg-blue-50 border border-blue-200 rounded-xl hover:bg-blue-100 transition-colors"
          >
            <Download size={18} className="text-blue-600" />
            <div className="text-left">
              <div className="font-medium text-blue-900">导出设置</div>
              <div className="text-sm text-blue-600">保存当前应用设置</div>
            </div>
          </button>
          
          <button
            onClick={handleImportSettings}
            className="w-full flex items-center gap-3 p-3 bg-green-50 border border-green-200 rounded-xl hover:bg-green-100 transition-colors"
          >
            <Upload size={18} className="text-green-600" />
            <div className="text-left">
              <div className="font-medium text-green-900">导入设置</div>
              <div className="text-sm text-green-600">从文件恢复设置</div>
            </div>
          </button>
        </div>
      </div>

      {/* 缓存管理 */}
      <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
          <RefreshCw size={18} />
          缓存管理
        </h3>
        <div className="space-y-3">
          <button
            onClick={handleClearCache}
            disabled={isLoading}
            className="w-full flex items-center gap-3 p-3 bg-orange-50 border border-orange-200 rounded-xl hover:bg-orange-100 transition-colors disabled:opacity-50"
          >
            <RefreshCw size={18} className={`text-orange-600 ${isLoading ? 'animate-spin' : ''}`} />
            <div className="text-left">
              <div className="font-medium text-orange-900">清理缓存</div>
              <div className="text-sm text-orange-600">清除应用缓存数据</div>
            </div>
          </button>
        </div>
      </div>

      {/* 危险操作 */}
      <div className="bg-white rounded-2xl border border-red-200 p-5 shadow-sm">
        <h3 className="font-semibold text-red-900 mb-4 flex items-center gap-2">
          <Shield size={18} />
          危险操作
        </h3>
        <div className="space-y-3">
          <button
            onClick={handleResetSettings}
            className="w-full flex items-center gap-3 p-3 bg-red-50 border border-red-200 rounded-xl hover:bg-red-100 transition-colors"
          >
            <Trash2 size={18} className="text-red-600" />
            <div className="text-left">
              <div className="font-medium text-red-900">重置设置</div>
              <div className="text-sm text-red-600">恢复所有设置到默认状态</div>
            </div>
          </button>
        </div>
      </div>
    </div>
  )

  const renderAboutSettings = () => {
    const versionInfo = getVersionInfo();
    
    return (
      <div className="space-y-4">
        <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm text-center">
          <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-blue-600 rounded-2xl mx-auto mb-4 flex items-center justify-center">
            <span className="text-white font-bold text-xl">A</span>
          </div>
          <h3 className="text-xl font-bold text-slate-900 mb-2">AIDE</h3>
          <p className="text-slate-600 mb-4">AI智能任务助手</p>
          <div className="space-y-2 text-sm text-slate-500">
            <p>版本: v{versionInfo.version}</p>
            <p>构建时间: {versionInfo.buildDate}</p>
            <p>环境: {versionInfo.environment === 'production' ? '生产版' : '开发版'}</p>
            <p>© 2024 AIDE Team</p>
          </div>
        </div>

      <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4">功能特性</h3>
        <div className="space-y-2 text-sm text-slate-600">
          <p>• 🤖 智能任务解析和管理</p>
          <p>• 🧠 AI驱动的个性化建议</p>
          <p>• 🔄 重复任务自动化</p>
          <p>• 📊 数据可视化分析</p>
          <p>• ☁️ 多设备数据同步</p>
          <p>• 📱 PWA桌面应用支持</p>
          <p>• 🔔 智能通知提醒</p>
          <p>• 💾 离线缓存功能</p>
        </div>
      </div>

      {/* AI助手设置 */}
      <div className="bg-white rounded-2xl border border-slate-200/60 p-5 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
          <Bot size={18} />
          AI助手设置
        </h3>
        <div className="space-y-3">
          <button
            onClick={() => setShowAISettings(true)}
            className="w-full flex items-center gap-3 p-3 bg-blue-50 border border-blue-200 rounded-xl hover:bg-blue-100 transition-colors"
          >
            <Bot size={18} className="text-blue-600" />
            <div className="text-left">
              <div className="font-medium text-blue-900">悬浮AI助手</div>
              <div className="text-sm text-blue-600">配置AI助手悬浮球显示和行为</div>
            </div>
            <ChevronRight size={16} className="text-blue-400 ml-auto" />
          </button>
        </div>
      </div>

      <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl border border-blue-200 p-5 shadow-sm">
        <h3 className="font-semibold text-blue-900 mb-3 flex items-center gap-2">
          <Smartphone size={18} />
          PWA桌面应用
        </h3>
        <div className="space-y-3 text-sm text-blue-700">
          <p>AIDE已支持PWA（渐进式Web应用），您可以：</p>
          <ul className="space-y-1 ml-4">
            <li>• 📲 安装到桌面，像原生应用一样使用</li>
            <li>• ⚡ 享受更快的启动速度</li>
            <li>• 🔔 接收系统级通知提醒</li>
            <li>• 💾 离线查看缓存的任务</li>
            <li>• 🖥️ 独立窗口运行，不依赖浏览器</li>
          </ul>
          <div className="mt-3 p-3 bg-blue-100 rounded-lg">
            <p className="text-xs text-blue-800">
              💡 <strong>安装提示</strong>：在支持的浏览器中，地址栏会显示安装图标，点击即可安装到桌面。
            </p>
          </div>
        </div>
      </div>
    </div>
    );
  };

  return (
    <div className="min-h-screen bg-slate-50">
      {/* Header */}
      <header className="sticky top-0 bg-white/95 backdrop-blur-sm shadow-sm border-b border-slate-200/60 z-10">
        <div className="flex items-center justify-between px-4 py-3 max-w-md mx-auto sm:max-w-lg md:max-w-xl lg:max-w-2xl xl:max-w-4xl">
          <button
            onClick={() => navigate('/profile')}
            className="p-2 text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg transition-all touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-slate-900">应用设置</h1>
          <div className="w-9 h-9" />
        </div>
      </header>

      {/* Tab Navigation */}
      <div className="bg-white border-b border-slate-200/60">
        <div className="flex px-4 max-w-md mx-auto sm:max-w-lg md:max-w-xl lg:max-w-2xl xl:max-w-4xl">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => navigate(`/settings?tab=${tab.id}`)}
              className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium transition-colors relative ${
                activeTab === tab.id
                  ? 'text-blue-600'
                  : 'text-slate-500 hover:text-slate-700'
              }`}
            >
              <tab.icon size={16} />
              <span>{tab.name}</span>
              {activeTab === tab.id && (
                <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600 rounded-full" />
              )}
            </button>
          ))}
        </div>
      </div>

      <main className="px-4 pb-6 mt-4 max-w-md mx-auto sm:max-w-lg md:max-w-xl lg:max-w-2xl xl:max-w-4xl">
        {activeTab === 'general' && renderGeneralSettings()}

        {activeTab === 'data' && renderDataSettings()}
        {activeTab === 'about' && renderAboutSettings()}
      </main>

      {/* AI助手设置弹窗 */}
      <FloatingAISettings
        isOpen={showAISettings}
        onClose={() => setShowAISettings(false)}
      />
    </div>
  )
}
